<!-- EpubSpreadsReader.vue -->
<template>
    <div class="epub-reader">
        <!-- 目录下拉 -->
        <select v-model="selectedToc" @change="onTocChange" class="toc-select">
            <option v-for="(chapter, index) in toc" :key="index" :value="chapter.href">
                {{ chapter.label }}
            </option>
        </select>

        <!-- 阅读容器 -->
        <div ref="viewer" class="spreads"></div>

        <!-- 翻页按钮 -->
        <a href="#" ref="prevButton" id="prev" class="arrow" :class="{ rtl: isRtl }" @click.prevent="goPrev">
            ‹
        </a>
        <a href="#" ref="nextButton" id="next" class="arrow" :class="{ rtl: isRtl }" @click.prevent="goNext">
            ›
        </a>

        <!-- 错误提示 -->
        <p v-if="error" class="error">{{ error }}</p>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, computed, watch } from 'vue';

// 类型定义（简化）
interface TocItem {
    label: string;
    href: string;
}

// Props（可选：支持传入 url 和 loc）
interface Props {
    url?: string;
    loc?: string;
}

const props = withDefaults(defineProps<Props>(), {
    url: 'https://s3.amazonaws.com/moby-dick/moby-dick.epub',
    loc: undefined
});

// Refs
const viewer = ref<HTMLElement | null>(null);
const prevButton = ref<HTMLAnchorElement | null>(null);
const nextButton = ref<HTMLAnchorElement | null>(null);

const toc = ref<TocItem[]>([]);
const selectedToc = ref<string>('');
const error = ref<string | null>(null);

let book: any = null;
let rendition: any = null;

// 是否为从右到左语言（RTL）
const isRtl = computed(() => {
    return book?.package?.metadata?.direction === 'rtl';
});

// ========== 初始化 ==========
onMounted(async () => {
    try {
        // 动态导入 epubjs
        const module = await import('epubjs');
        const ePub = module.default || module;

        book = ePub(props.url);

        if (!viewer.value) throw new Error('Viewer 容器未挂载');

        // 渲染为双页模式
        rendition = book.renderTo(viewer.value, {
            width: '100%',
            height: 600,
            spread: 'always' // 双页布局
        });

        // 显示指定位置或默认位置
        await rendition.display(props.loc);

        // 加载目录
        book.loaded.navigation.then((nav: any) => {
            toc.value = nav.toc;
            // 设置默认选中项
            const current = book.navigation.get(rendition.currentLocation()?.start?.href);
            selectedToc.value = current?.href || toc.value[0]?.href;
        });

        // ========== 事件监听 ==========

        // 翻页按钮控制显隐
        rendition.on('relocated', (location: any) => {
            const prev = isRtl.value ? nextButton.value : prevButton.value;
            const next = isRtl.value ? prevButton.value : nextButton.value;

            if (next) {
                next.style.visibility = location.atEnd ? 'hidden' : 'visible';
            }
            if (prev) {
                prev.style.visibility = location.atStart ? 'hidden' : 'visible';
            }

            // 更新下拉选中
            const current = book.navigation.get(location.start.href);
            if (current) {
                selectedToc.value = current.href;
            }
        });

        // 布局变化（单页/双页）
        rendition.on('layout', (layout: any) => {
            const el = viewer.value;
            if (el) {
                if (layout.spread) {
                    el.classList.remove('single');
                } else {
                    el.classList.add('single');
                }
            }
        });

        // 键盘事件
        const keyListener = (e: KeyboardEvent) => {
            if (e.keyCode === 37) {
                // 左键
                isRtl.value ? rendition.next() : rendition.prev();
            } else if (e.keyCode === 39) {
                // 右键
                isRtl.value ? rendition.prev() : rendition.next();
            }
        };

        document.addEventListener('keyup', keyListener);

        // 组件卸载时清理
        onBeforeUnmount(() => {
            document.removeEventListener('keyup', keyListener);
            if (book && typeof book.destroy === 'function') {
                book.destroy();
            }
        });
    } catch (err: any) {
        console.error('EPUB 加载失败:', err);
        error.value = err.message || '加载失败';
    }
});

// ========== 方法 ==========
const goPrev = () => {
    isRtl.value ? rendition.next() : rendition.prev();
};

const goNext = () => {
    isRtl.value ? rendition.prev() : rendition.next();
};

const onTocChange = () => {
    rendition.display(selectedToc.value);
};

// ========== 销毁 ==========
onBeforeUnmount(() => {
    if (book && typeof book.destroy === 'function') {
        book.destroy();
    }
    book = null;
    rendition = null;
});
</script>

<style scoped>
.epub-reader {
    position: relative;
    max-width: 100%;
    margin: 0 auto;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}

.toc-select {
    width: 100%;
    padding: 8px;
    margin-bottom: 10px;
    font-size: 14px;
    border: 1px solid #ccc;
    border-radius: 4px;
}

.spreads {
    width: 100%;
    height: 90vh;
    overflow: hidden;
    border: 1px solid #ddd;
    background: #fff;
}

.spreads.single {
    /* 可选：单页模式样式 */
}

.arrow {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    width: 40px;
    height: 40px;
    line-height: 40px;
    margin: -20px 0 0;
    font-size: 30px;
    font-weight: bold;
    text-align: center;
    color: white;
    background: rgba(0, 0, 0, 0.5);
    border-radius: 50%;
    text-decoration: none;
    z-index: 10;
    cursor: pointer;
    user-select: none;
    opacity: 0.8;
    transition: opacity 0.2s;
}

.arrow:hover {
    opacity: 1;
}

#prev {
    left: 10px;
}

#next {
    right: 10px;
}

#prev.rtl {
    left: auto;
    right: 10px;
}

#next.rtl {
    right: auto;
    left: 10px;
}

.error {
    color: #d32f2f;
    background: #ffebee;
    padding: 10px;
    border-radius: 4px;
    font-size: 14px;
    margin-top: 10px;
}
</style>